﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;
using System.Web.Security;
using System.Web.Configuration;
using DoeLibsMVC.Security;

//using WebApiContrib.Formatting.Jsonp;
using System.Net.Http.Formatting;

namespace DoeLibsMVC
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
		private DailyChecks _dailyCheckTimer = new DailyChecks();

        protected void Application_Start()
        {
            DoeObjects.Settings.ConnectionString = WebConfigurationManager.ConnectionStrings["DoeLibString"].ConnectionString;
			DoeObjects.Settings.SimpleMailClient = new System.Net.Mail.SmtpClient
			{
				Host = WebConfigurationManager.AppSettings["SmtpClientHost"],
				Port = Convert.ToInt32(WebConfigurationManager.AppSettings["SmtpClientPort"]),
				Credentials = new System.Net.NetworkCredential(
					WebConfigurationManager.AppSettings["SmtpClientUsername"],
					WebConfigurationManager.AppSettings["SmtpClientPassword"]),
				DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
				EnableSsl = true
			};
			DoeObjects.Settings.SenderAddress = new System.Net.Mail.MailAddress(
				WebConfigurationManager.AppSettings["MailSenderAddress"],
				WebConfigurationManager.AppSettings["MailSenderDisplayName"]);

			TimeSpan expireNotificationTime;
			TimeSpan.TryParse(WebConfigurationManager.AppSettings["ExpireNotificationTime"],
				out expireNotificationTime);
			DoeObjects.Settings.ExpireNotificationTime = expireNotificationTime;
			TimeSpan studentExpireTime;
			TimeSpan.TryParse(WebConfigurationManager.AppSettings["StudentExpireTime"],
				out studentExpireTime);
			DoeObjects.Settings.StudentExpireTime = studentExpireTime;

			try
			{
				DoeObjects.Settings.QueueMailsFrom = TimeSpan.Parse(
					WebConfigurationManager.AppSettings["QueueMailsFrom"]);
				DoeObjects.Settings.QueueMailsTo = TimeSpan.Parse(
					WebConfigurationManager.AppSettings["QueueMailsTo"]);
				DoeObjects.Settings.UseMailQueueing = true;
			}
			catch (Exception e)
			{
				DoeObjects.Settings.UseMailQueueing = false;
			}

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //GlobalConfiguration.Configuration.AddJsonpFormatter();
            //GlobalConfiguration.Configuration.Formatters.Insert(0, new DoeLibsMVC.JSONPFormatter());

            GlobalConfiguration.Configuration.Services.RemoveAll(
            typeof(System.Web.Http.Validation.ModelValidatorProvider),
            v => v is System.Web.Http.Validation.Providers.InvalidModelValidatorProvider);

			_dailyCheckTimer.Start();
        }

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            //HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            //if (authCookie != null)
            //{

            //    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            //    DoeObjects.User user = null;
            //    if ((user = DoeObjects.User.getUserByUserId(Convert.ToInt32(authTicket.UserData))) != null)
            //    {
            //        HttpContext.Current.User = new CustomPrincipal(Convert.ToInt32(authTicket.UserData));
            //    }
            //    else
            //    {
            //        HttpContext.Current.User = null;
            //    }
            //}

            string authCookieValue = Security.SecurityHelper.getAuthCookieValue();

            if (!string.IsNullOrEmpty(authCookieValue))
            {
                DoeObjects.User user = null;
                if ((user = DoeObjects.User.getUserByUserId(Convert.ToInt32(authCookieValue))) != null)
                {
                    HttpContext.Current.User = new CustomPrincipal(Convert.ToInt32(authCookieValue));
                }
                else
                {
                    HttpContext.Current.User = null;
                }
            }

        }
    }
}